package cloud.lysky.java.on.concurrent.synchronized_;

/**
 * @author luoly
 * @describe 演示Java内存模型带来的线程安全问题
 * @date 2022-11-17 22:12
 **/
public class SyncDemo {
    private static int counter = 0;

    public synchronized static void increment() {
        counter++;
    }

    public synchronized static void decrement() {
        counter--;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                increment();
            }
        },"t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                decrement();
            }
        },"t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("counter=" + counter);
    }
}
